package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *兆永 http
 */
public class SmsApiZHAOYONGhttpSMS extends GateWayHttpAbstract
{

    public SmsApiZHAOYONGhttpSMS(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();
        try{
            String t = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
            params.put("userid", paramsMaps.get("userid"));
            params.put("account", paramsMaps.get("account"));
            params.put("password", paramsMaps.get("password"));
            params.put("mobile", mt.getPhone());
            params.put("content", URLEncoder.encode(mt.getSmsContent(),"utf-8"));
            params.put("action", "send");
            params.put("sendTime", t);
            params.put("extno", mt.getSmsREQMessage().getSendnumber());
        }
        catch (UnsupportedEncodingException e)
        {
            logger.error("网关:{}, 响应:{}", this.gateWayID, e);
        }

        String json =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/sms.aspx ", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);
        
        List<SMSSRMessage> resultList = Lists.newArrayList();

        Document doc;
        try {
            doc = DocumentHelper.parseText(json);
            Element root = doc.getRootElement();
            SMSSRMessage message = initGatewayResultMessage(json, mt, "returnstatus");
            String resultCode = null;
            String resultMessage = null;
            String taskid = null;
            if(StringUtils.equals(message.getResult(), "F10199")) {
                resultCode = String.valueOf(root.element("returnstatus").getStringValue());
                resultMessage = String.valueOf(root.element("message").getStringValue());
                if(StringUtils.equals(resultCode, "ok")) {
                    taskid = String.valueOf(root.element("taskID").getStringValue());
                }
                message.setMsgkey(mt.getPhone());
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "ok");
            }

            resultList.add(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {


        logger.info("{}网关推送状态报告:{}", gateWayID, text);

        Document doc;
        try {
        	if(StringUtils.isNotBlank(text)) {
                doc = DocumentHelper.parseText(text);
                Element root = doc.getRootElement();
                if (text.contains("statusbox")) {
                    List<Element> itemElements = root.elements("statusbox");
                    for (Element data : itemElements) {
                        SMSRTMessage smsRtMessage = initSmsRtMessage(data.element("taskid").getStringValue(), data.element("mobile").getStringValue(),data.element("mobile").getStringValue(),
                                data.element("status").getStringValue(), "10");
                        rtList.add(smsRtMessage);
                    }
                }
            }
        } catch(DocumentException e) {
        	 return new SmsHttpMsgResponse("error");
        } catch(Exception e) {
        	 return new SmsHttpMsgResponse("error");
        }
        return null;
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
    	logger.info("{}网关推送用户上行:{}", gateWayID, text);
        Document doc;
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("ok");
    	try {
            if(StringUtils.isNotBlank(text)) {
                if (text.contains("callbox")) {
                    doc = DocumentHelper.parseText(text);
                    Element root = doc.getRootElement();
                    List<Element> itemElements = root.elements("statusbox");
                    for (Element data : itemElements) {
                        SMSMOMessage sMSMOMessage = new SMSMOMessage();
                        sMSMOMessage.setGateWayID(gateWayID);
                        sMSMOMessage.setMsgContent(data.element("content").getStringValue());
                        sMSMOMessage.setMsgid(data.element("taskid").getStringValue());
                        sMSMOMessage.setPhone(data.element("mobile").getStringValue());
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                        sMSMOMessage.setUuid(UUID.randomUUID().toString());
                        moList.add(sMSMOMessage);
                    }
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
            smsHttpMsgResponse.setResult("error");
            return smsHttpMsgResponse;
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        Map<String,Object> params = Maps.newHashMap();
        params.put("userid", paramsMaps.get("userid"));
        params.put("account", paramsMaps.get("account"));
        params.put("password", paramsMaps.get("password"));
        params.put("action", "query");
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/statusApi.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
//        logger.info("主动查询订单结果{}，通道{}", result, gateWayID);
        return result;
    }

    @Override
    public String queryDeliver(String jsonText)
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("userid", paramsMaps.get("userid"));
        params.put("account", paramsMaps.get("account"));
        params.put("password", paramsMaps.get("password"));
        params.put("action", "query");
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/callApi.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
//        logger.info("主动查询上行回复{}，通道{}", result, gateWayID);
        return  result;
    }
    
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("action","overage");
        params.put("userid",paramsMaps.get("userid"));
        params.put("account",paramsMaps.get("account"));
        params.put("password",DigestUtils.md5Hex(paramsMaps.get("password")));
        String apiUrl = paramsMaps.get("apiUrl") + "/sms.aspx";
        String param = Joiner.on("&").withKeyValueSeparator("=").join(params);
        System.out.println("apiUrl=" + apiUrl + ",param=" + param);
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/sms.aspx" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        Document doc;
        try {
            doc = DocumentHelper.parseText(result);
            Element root = doc.getRootElement();
            if (StringUtils.equals("Success",root.element("returnstatus").getStringValue())) {
                return  "余额：" + root.element("overage").getStringValue() + ", 发送条数：" + root.element("sendTotal").getStringValue();
            }
        }catch (Exception e) {
            e.printStackTrace();
            return "余额查询失败";
        }

        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
        String params = "{\"userid\":\"311\",\"account\":\"b13588942283\",\"password\":\"yuan2018\",\"apiUrl\":\"http://121.40.143.163:6666\"}";
    	SmsApiZHAOYONGhttpSMS api = new SmsApiZHAOYONGhttpSMS("JIESMS", params);

    	String balance = api.balance();
        System.out.println(balance);
    }
    
}